# USAGE
# python barcode_scanner_video.py

# import the necessary packages
from imutils.video import VideoStream
from pyzbar import pyzbar
import argparse
import datetime
import imutils
import time
import cv2
import json

# construct the argument parser and parse the arguments
#cap = cv2.VideoCapture(0)


def is_json(myjson):
    try:
        json.loads(myjson)
    except ValueError:
        return False
    return True

#Loading images
img_all = cv2.imread("all.jpg")
img_harm = cv2.imread("harm.jpg")
img_other = cv2.imread("other.jpg")
img_food = cv2.imread("food.jpg")
img_recycle = cv2.imread("recycle.jpg")

cv2.imshow("Original image", img_all)
cv2.waitKey(5)
ap = argparse.ArgumentParser()
ap.add_argument("-o", "--output", type=str, default="barcodes.csv",
	help="path to output CSV file containing barcodes")
args = vars(ap.parse_args())

# initialize the video stream and allow the camera sensor to warm up
print("Garbage classification QR code identification function launched...")
# vs = VideoStream(src=0).start()
vs = VideoStream(src=0).start()
time.sleep(0.5)

# open the output CSV file for writing and initialize the set of
# barcodes found thus far
csv = open(args["output"], "w")
found = set()

# loop over the frames from the video stream
while True:
	# grab the frame from the threaded video stream and resize it to
	# have a maximum width of 400 pixels
	frame = vs.read()
	frame = imutils.resize(frame, width=400)

	# find the barcodes in the frame and decode each of the barcodes
	barcodes = pyzbar.decode(frame)

	# loop over the detected barcodes
	for barcode in barcodes:
		# extract the bounding box location of the barcode and draw
		# the bounding box surrounding the barcode on the image
		(x, y, w, h) = barcode.rect
		cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)

		# the barcode data is a bytes object so if we want to draw it
		# on our output image we need to convert it to a string first
		barcodeData = barcode.data.decode("utf-8")
		barcodeType = barcode.type
		
		# draw the barcode data and barcode type on the image
		if(is_json(barcodeData)):
			data_dict = json.loads(barcodeData)
			text = "The type of garbage is {},No is {}".format(data_dict['category'],data_dict['no'])
			cv2.putText(frame, text, (x, y - 10),
				cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
			if (data_dict['category'] == 'harm'):
				cv2.imshow("Original image", img_harm)
				cv2.waitKey(2)
			elif (data_dict['category'] == 'other'):
				cv2.imshow("Original image", img_other)
				cv2.waitKey(2)
			elif (data_dict['category'] == 'recycle'):
				cv2.imshow("Original image", img_recycle)
				cv2.waitKey(2)
			elif (data_dict['category'] == 'food'):
				cv2.imshow("Original image", img_food)
				cv2.waitKey(2)
			else:
				cv2.imshow("Original image", img_all)
				cv2.waitKey(2)

		
		elif(not is_json(barcodeData)):
			data_dict['category'] == 0
			false_text = "Garbage sorting QR codes are not legal!"
			cv2.putText(frame, false_text, (x, y - 10),
				cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
			img = cv2.imread("all.jpg")
			cv2.imshow("Original image", img_all)
			cv2.waitKey(2)
			
			
        
		

		# if the barcode text is currently not in our CSV file, write
		# the timestamp + barcode to disk and update the set
		if barcodeData not in found:
			data_dict['category'] == 0
			cv2.imshow("Original image", img_all)
			cv2.waitKey(2)
	# show the output frame
	cv2.imshow("Barcode Scanner", frame)
	key = cv2.waitKey(1) & 0xFF
 
	# if the `q` key was pressed, break from the loop
	if key == ord("q"):
		break

# close the output CSV file do a bit of cleanup
print("Garbage sorting QR code recognition turned off...")
csv.close()
cv2.destroyAllWindows()
vs.stop()